﻿using System;
using System.Data;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Text;
using System.Web.Security;
using System.Web;

namespace Vehicle.Common
{
  public static  class TextHelper
    {
        /// 从前台获取的带空格字符串的处理 
        /// 待处理字符串 
        /// 处理后的字符串 
        public static string FormatNullString(string s)
        {
            s = s.Replace(" ", " ");
            return s.Trim();
        }

        public static byte StringToByte(string str)
        {
            byte ret = 0;

            //将字符形式的Bool转换 
            if (str == "True")
            {
                str = "1";
            }

            try
            {
                ret = Convert.ToByte(str, 2);
            }
            catch
            { }

            return ret;
        }

        ///  
        /// 将字符串转换为整数 
        ///  
        /// 待转换的字符串 
        /// 转换后的整数 
        public static int StringToInt(string str)
        {
            int ret = 0;
            try
            {
                ret = int.Parse(str);
            }
            catch
            {
            }

            return ret;
        }
        ///  
        /// 将字符串转换为整数 
        ///  
        /// 待转换的字符串 
        /// 转换后的整数 
        public static DateTime StringToDateTime(string str)
        {
            DateTime ret = DateTime.Now;
            try
            {
                ret = DateTime.Parse(str);
            }
            catch
            {
            }

            return ret;
        }

        ///  
        /// 将字符串转换为浮点数 
        ///  
        /// 待转换的字符串 
        /// 转换后的浮点数 
        public static double StringToDouble(string str)
        {
            double ret = 0;

            try
            {
                ret = double.Parse(str);
            }
            catch
            { }

            return ret;
        }
        ///  
        /// 将字符串转换为浮点数 
        ///  
        /// 待转换的字符串 
        /// 转换后的浮点数 
        public static float StringTofloat(string str)
        {
            float ret = 0;

            try
            {
                ret = float.Parse(str);
            }
            catch
            { }

            return ret;
        }
        public static decimal StringToDecimal(string str)
        {
            decimal ret = 0;
            try
            {
                ret = decimal.Parse(str);
            }
            catch
            {
            }
            return ret;
        }


        /// <summary>
        /// 字符串清理
        /// </summary>
        /// <param name="inputString"></param>
        /// <param name="maxLength"></param>
        /// <returns></returns>
        public static string InputText(string inputString, int maxLength)
        {
            StringBuilder retVal = new StringBuilder();

            // 检查是否为空
            if ((inputString != null) && (inputString != String.Empty))
            {
                inputString = inputString.Trim();

                //检查长度
                if (inputString.Length > maxLength)
                    inputString = inputString.Substring(0, maxLength);

                //替换危险字符
                for (int i = 0; i < inputString.Length; i++)
                {
                    switch (inputString[i])
                    {
                        case '"':
                            retVal.Append("&quot;");
                            break;
                        case '<':
                            retVal.Append("&lt;");
                            break;
                        case '>':
                            retVal.Append("&gt;");
                            break;
                        default:
                            retVal.Append(inputString[i]);
                            break;
                    }
                }
                retVal.Replace("'", " ");// 替换单引号
            }
            return retVal.ToString();

        }
        /// <summary>
        /// 转换成 HTML code
        /// </summary>
        /// <param name="str">string</param>
        /// <returns>string</returns>
        public static string Encode(string str)
        {
            str = str.Replace("&", "&amp;");
            str = str.Replace("'", "''");
            str = str.Replace("\"", "&quot;");
            str = str.Replace(" ", "&nbsp;");
            str = str.Replace("<", "&lt;");
            str = str.Replace(">", "&gt;");
            str = str.Replace("\r", "<br/>").Replace(" ", " ");
            return str;
        }
        /// <summary>
        ///解析html成 普通文本
        /// </summary>
        /// <param name="str">string</param>
        /// <returns>string</returns>
        public static string Decode(string str)
        {
            str = str.Replace("<br>", "\n");
            str = str.Replace("&gt;", ">");
            str = str.Replace("&lt;", "<");
            str = str.Replace("&nbsp;", " ");
            str = str.Replace("&quot;", "\"");
            return str;
        }
        /// <summary>
        /// 输入安全过滤
        /// </summary>
        /// <param name="html">文本</param>
        /// <returns>过滤后的文本</returns>
        public static string CheckStr(string html)
        {
            html = Regex.Replace(html, @"<\s*(\/?)\s*(script|i?frame|style|html|body|title|link|meta|object|\?|\%)([^>]*?)>", string.Empty, RegexOptions.IgnoreCase);
            html = Regex.Replace(html, @"(<[^>]*)on[a-zA-Z]+\s*=([^>]*>)", "$1>", RegexOptions.IgnoreCase);
            return html;
        }

        /// <summary>
        /// 转换为MD5值
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string ToMD5(this string s)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "MD5").ToLower();
        }

        public static string UrlEncode(this string s)
        {
            return HttpContext.Current.Server.HtmlEncode(s);
        }

        public static string UrlDecode(this string s)
        {
            return HttpContext.Current.Server.HtmlDecode(s);
        }

        public static string HtmlEncode(this string s)
        {
            s = HttpContext.Current.Server.HtmlEncode(s);
            //s=Regex.Replace(s, @"\r*\n", "<br />");
            s = s.Replace("\r\n", "<br />");
            s = s.Replace("\r", "<br />");
            s = s.Replace("\n", "<br />");
            return s;
        }

        public static string HtmlDecode(this string s)
        {
            return HttpContext.Current.Server.HtmlDecode(s);
        }
        #region ========加密========

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Encrypt(string Text)
        {
            return Encrypt(Text, "M-TEAR");
        }
        /// <summary> 
        /// 加密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Encrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray;
            inputByteArray = Encoding.Default.GetBytes(Text);
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return ret.ToString();
        }

        #endregion

        #region ========解密========


        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Decrypt(string Text)
        {
            return Decrypt(Text, "M-TEAR");
        }
        /// <summary> 
        /// 解密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Decrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            int len;
            len = Text.Length / 2;
            byte[] inputByteArray = new byte[len];
            int x, i;
            for (x = 0; x < len; x++)
            {
                i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Encoding.Default.GetString(ms.ToArray());
        }

        #endregion
    }
}

